#pragma once
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cstring>
#include <unistd.h>
#include <cerrno>
using namespace std;
#define PATH "/home/user100"
#define proj_id 111
#define SIZE 4096

key_t Getkey()
{
    key_t key = ftok(PATH, proj_id);
    if (key < 0)
    {
        cout << "ftok fail errno is " << errno << " error string is " << strerror(errno) << endl;
        return -1;
    }
    return key;
}

int ServerGetshm(key_t key)
{
    int shmid = shmget(key, SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid < 0)
    {
        cout << "Server Get shm fail errno is " << errno << " error string is " << strerror(errno) << endl;
        return -1;
    }
    cout << "make shm success" << endl;
    return shmid;
}
int ClientGetshm(key_t key)
{
    int shmid = shmget(key, SIZE, IPC_CREAT | 0666);
    if (shmid > 0)
        cout << "Client Get shm success" << endl;
    return shmid;
}

void *Attach(int shmid)
{
    void *addr = shmat(shmid, nullptr, 0);
    if ((long long)addr == -1)
    {
        cout << "shmat fail errno is " << errno << " error string is " << strerror(errno) << endl;
        return nullptr;
    }
    cout << "shmat success" << endl;
    return addr;
}

int Detach(void *addr)
{
    int ret1 = shmdt(addr);
    if (ret1 < 0)
    {
        cout << "shmdt fail errno is " << errno << " error string is " << strerror(errno) << endl;
        return -1;
    }
    cout << "shmdt success" << endl;
    return 0;
}

int removeshm(int shmid)
{
    int ret = shmctl(shmid, IPC_RMID, nullptr);
    if (ret < 0)
    {
        cout << "remove shm fail errno is " << errno << " error string is " << strerror(errno) << endl;
        return -1;
    }
    cout << "remove shm success,shmid is " << shmid << endl;
    return 0;
}